package com.shareit.ocr.domain.simulator;

import java.util.UUID;

import org.slf4j.Logger;

import com.shareit.ocr.domain.SimulatorRequestInfo;
import com.shareit.ocr.domain.template.InvoiceDataTemplate;
import com.shareit.ocr.enums.ResultEnum;
import com.shareit.ocr.exception.SimulatorException;
import com.shareit.ocr.properties.SimulatorProperties;

public abstract class BaseSimulator {
	
	//UUID
	private String id="";
	
	//状态
	protected boolean status;
	
	protected SimulatorProperties simulatorProperties;
	
	public BaseSimulator() {
	  
		id = UUID.randomUUID().toString();
		status = false;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public SimulatorProperties getSimulatorProperties() {
		return simulatorProperties;
	}

	public void setSimulatorProperties(SimulatorProperties simulatorProperties) {
		this.simulatorProperties = simulatorProperties;
	}
	
	public boolean getStatus() {
		return status;
	}
	
	public void infoLog(String title,Object obj) {
		String detaillog ="";
		detaillog = "<" + this.getId() + "> :" + title + ">>>{}";
		getLogger().info(detaillog,obj);	
	}
	
	public void infoLog(String log) {
		String detaillog ="";
		detaillog = "<" + this.getId() + "> :" + log;
		getLogger().info(detaillog);	
	}
	
	public void start(InvoiceDataTemplate idt) {
		
		infoLog("begin start");
		int try_count = 0;
		
		while(try_count <= this.simulatorProperties.getTryCount()) {
			
			try_count =try_count + 1;
			infoLog("尝试第[" + try_count + "]次获取数据");
			try {
				infoLog("尝试第[" + try_count + "]次获取验证码");
				getYzmCode(idt);
				infoLog("第" + try_count + "次获取验证码完成，开始获取完整发票数据.");
				getDetailInfo(idt);
				infoLog("第" + try_count + "次获取完整发票数据完成.");
				status = true;
				break;
			}catch(SimulatorException se) {
				infoLog("第[" + try_count + "]次获取数据发生错误:" + se.getMessage());
				if(se.getResultEnum() == ResultEnum.INVOICE_VERIFY_NO_COUNT) {
					throw se;
				}
				if(try_count == this.simulatorProperties.getTryCount()) {
					throw se;
				}else
					continue;
			}catch(Exception e) {
				if(try_count == this.simulatorProperties.getTryCount()) {
					e.printStackTrace();
					throw new SimulatorException(ResultEnum.UNKOWN_ERROR);
				}else
					continue;
			}
		}
	}
	
	/**
	 * 检查请求参数是否合法
	 * @param sri
	 */
	public void checkValid(SimulatorRequestInfo sri){
			
	}
	
	abstract public Logger getLogger();
	abstract public void getYzmCode(InvoiceDataTemplate idt) throws Exception;
	abstract public void getDetailInfo(InvoiceDataTemplate idt) throws Exception;
	abstract public void close();
	
	
}
